﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace Having.Site.Base
{
    /// <summary>
    /// 低容错，针对顺序操作的方法，添加后，该方法将在服务器自动运行（单一执行的，不重复的，有时候响应较慢的）
    /// </summary>
    public static class WorkQueue
    {
        /// <summary>
        /// 队列列表
        /// </summary>
        public static Queue<QueKey> list = new Queue<QueKey>();
        static object obj = new object();
        /// <summary>
        /// 添加到队列
        /// </summary>
        /// <param name="c"></param>
        public static void Add(Action c)
        {
            lock (obj)
            {
                var pk = new QueKey(c);
                list.Enqueue(pk);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="qk"></param>
        /// <param name="ischeck">检测是否存在，不存在才能加入(根据key来判断)</param>
        public static bool Add(QueKey qk,bool ischeck)
        {
            var isok = true;
            lock (obj)
            {
                if (!ischeck)
                {
                    if (!string.IsNullOrWhiteSpace(qk.key))
                    {
                        var it = list.Count(m => m.key == qk.key);
                        isok = !(it > 0);
                    }
                }
                if (isok)
                {
                    list.Enqueue(qk);
                }
            }
            return isok;

        }
        public static void Add(QueKey qk)
        {
            lock (obj)
            {
                list.Enqueue(qk);
            }
        }
    }

    /// <summary>
    /// 
    /// </summary>
    public class QueKey
    {
        /// <summary>
        /// 名称
        /// </summary>
        public string key { set; get; }
        
        /// <summary>
        /// 执行的方法
        /// </summary>
        public Action ac { set; get; }

        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="_ac"></param>
        /// <param name="_key"></param>
        public QueKey(Action _ac, string _key=null)
        {

            this.ac = _ac;
            this.key = _key;
        }
    }

    
}
